<template>
  <div class="report-templates-page" v-loading="loading">
    <ReportsSearchCard title="搜索与筛选">
      <el-form :model="searchForm" class="search-form">
        <div class="search-form-content">
          <div class="search-form-fields">
            <el-form-item label="模板分组">
              <el-input
                v-model="searchForm.group"
                placeholder="输入分组名称，如 starrocks/cps"
                clearable
                style="width: 200px"
              />
            </el-form-item>

            <el-form-item label="启用状态">
              <el-select
                v-model="searchForm.is_active"
                placeholder="选择状态"
                clearable
                style="width: 140px"
                popper-class="batch-dialog-select-popper"
                popper-append-to-body
              >
                <el-option label="全部" :value="''" />
                <el-option label="启用" :value="true" />
                <el-option label="禁用" :value="false" />
              </el-select>
            </el-form-item>
          </div>

          <div class="search-form-actions">
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button type="warning" @click="handleReset">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </div>
        </div>
      </el-form>
    </ReportsSearchCard>

    <ReportsTableCard>
      <template #title>
        <el-icon><List /></el-icon>
        <span>模板列表</span>
      </template>
      <template #actions>
        <el-button type="success" @click="handleRefresh" class="refresh-btn" :loading="loading" size="small">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
        <div class="table-info">
          <div class="pagination-control-wrapper clickable" @click="togglePagination">
            <span class="page-count">本页 {{ templates.length }} 条</span>
            <div class="divider"></div>
            <span class="pagination-info">
              {{ currentPage }}/{{ Math.ceil(total / pageSize) || 1 }}
            </span>
            <el-icon class="pagination-toggle-icon">
              <ArrowUp v-if="paginationVisible" />
              <ArrowDown v-else />
            </el-icon>
          </div>
        </div>
      </template>

      <el-table
        :data="templates"
        v-loading="loading"
        @sort-change="handleSortChange"
        :default-sort="{ prop: 'template_group', order: 'ascending' }"
        class="enhanced-table"
        style="width: 100%"
        :height="600"
        table-layout="fixed"
        :stripe="false"
        :border="false"
      >
        <el-table-column prop="template_name" label="模板名称" min-width="200" show-overflow-tooltip fixed="left" />

        <el-table-column prop="template_group" label="分组" min-width="140" show-overflow-tooltip />

        <el-table-column prop="template_code" label="模板编码" min-width="220" show-overflow-tooltip />

        <el-table-column label="状态" width="120" align="center">
          <template #default="{ row }">
            <el-switch
              v-model="row.is_active"
              :active-value="1"
              :inactive-value="0"
              active-text=""
              inactive-text=""
              @change="(value) => handleToggleStatus(row, value)"
            />
          </template>
        </el-table-column>

        <el-table-column label="创建时间" min-width="180" show-overflow-tooltip sortable="custom" prop="created_at">
          <template #default="{ row }">
            {{ formatDateTime(row.created_at) }}
          </template>
        </el-table-column>

        <el-table-column label="更新时间" min-width="180" show-overflow-tooltip sortable="custom" prop="updated_at">
          <template #default="{ row }">
            {{ formatDateTime(row.updated_at) }}
          </template>
        </el-table-column>

        <el-table-column label="操作" width="220" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-tooltip content="查看详情" placement="top">
                <el-button
                  type="success"
                  size="small"
                  @click="handleView(row)"
                  circle
                >
                  <el-icon><View /></el-icon>
                </el-button>
              </el-tooltip>
              <el-tooltip content="编辑模板" placement="top">
                <el-button
                  type="primary"
                  size="small"
                  @click="handleEdit(row)"
                  circle
                >
                  <el-icon><Edit /></el-icon>
                </el-button>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <template #pagination>
        <transition name="pagination-slide">
          <div v-show="paginationVisible" class="pagination-section">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :total="total"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, sizes, prev, pager, next, jumper"
              @current-change="fetchTemplates"
              @size-change="fetchTemplates"
              background
            />
          </div>
        </transition>
      </template>
    </ReportsTableCard>

    <el-dialog
      v-model="viewDialogVisible"
      width="800px"
      :close-on-click-modal="false"
      append-to-body
      class="unified-dialog"
    >
      <template #header>
        <DialogHeader
          :icon="View"
          title="模板详情"
          :description="currentTemplate?.template_name || ''"
          type="success"
        />
      </template>

      <div v-if="currentTemplate" class="dialog-content" v-loading="detailLoading">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="模板编码">
            {{ currentTemplate.template_code }}
          </el-descriptions-item>
          <el-descriptions-item label="模板名称">
            {{ currentTemplate.template_name }}
          </el-descriptions-item>
          <el-descriptions-item label="模板分组">
            <el-tag :type="getGroupType(currentTemplate.template_group)">
              {{ currentTemplate.template_group || '-' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="版本">
            v{{ currentTemplate.version || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="currentTemplate.is_active ? 'success' : 'info'" size="small">
              {{ currentTemplate.is_active ? '启用' : '禁用' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="输出格式" :span="2">
            <el-tag
              v-for="fmt in (currentTemplate.output_formats || [])"
              :key="fmt"
              size="small"
              class="output-format-tag"
            >
              {{ fmt?.toUpperCase() }}
            </el-tag>
            <span v-if="!currentTemplate.output_formats || !currentTemplate.output_formats.length">-</span>
          </el-descriptions-item>
          <el-descriptions-item label="描述" :span="2">
            <div class="description-text">{{ currentTemplate.description || '-' }}</div>
          </el-descriptions-item>
          <el-descriptions-item label="参数定义" :span="2">
            <div class="json-block-wrapper">
              <div class="json-block-header">
                <span>JSON</span>
                <div class="json-actions">
                  <el-button
                    type="primary"
                    text
                    size="small"
                    @click="toggleJsonSection('param')"
                  >
                    <el-icon :class="['json-toggle-icon', { expanded: jsonExpanded.param }]">
                      <ArrowDown />
                    </el-icon>
                    {{ jsonExpanded.param ? '收起' : '展开' }}
                  </el-button>
                  <el-divider direction="vertical" class="json-action-divider" />
                  <el-button
                    type="primary"
                    text
                    size="small"
                    @click="handleCopyJson(currentTemplate.param_schema, '参数定义')"
                  >
                    <el-icon><CopyDocument /></el-icon>
                    复制
                  </el-button>
                </div>
              </div>
              <transition name="json-collapse">
                <pre v-show="jsonExpanded.param" class="json-block">{{ formatJson(currentTemplate.param_schema) }}</pre>
              </transition>
              <div v-show="!jsonExpanded.param" class="json-collapsed-placeholder">
                JSON 内容较长，点击“展开”查看
              </div>
            </div>
          </el-descriptions-item>
          <el-descriptions-item label="默认参数" :span="2">
            <div class="json-block-wrapper">
              <div class="json-block-header">
                <span>JSON</span>
                <div class="json-actions">
                  <el-button
                    type="primary"
                    text
                    size="small"
                    @click="toggleJsonSection('default')"
                  >
                    <el-icon :class="['json-toggle-icon', { expanded: jsonExpanded.default }]">
                      <ArrowDown />
                    </el-icon>
                    {{ jsonExpanded.default ? '收起' : '展开' }}
                  </el-button>
                  <el-divider direction="vertical" class="json-action-divider" />
                  <el-button
                    type="primary"
                    text
                    size="small"
                    @click="handleCopyJson(currentTemplate.default_params, '默认参数')"
                  >
                    <el-icon><CopyDocument /></el-icon>
                    复制
                  </el-button>
                </div>
              </div>
              <transition name="json-collapse">
                <pre v-show="jsonExpanded.default" class="json-block">{{ formatJson(currentTemplate.default_params) }}</pre>
              </transition>
              <div v-show="!jsonExpanded.default" class="json-collapsed-placeholder">
                JSON 内容较长，点击“展开”查看
              </div>
            </div>
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="viewDialogVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog
      v-model="editDialogVisible"
      width="600px"
      :close-on-click-modal="false"
      append-to-body
      class="unified-dialog"
    >
      <template #header>
        <DialogHeader
          :icon="Edit"
          title="编辑模板"
          :description="editForm.template_name || ''"
          type="primary"
        />
      </template>

      <el-form :model="editForm" label-width="100px">
        <el-alert
          title="仅允许编辑模板名称、描述和启用状态，不支持修改参数定义。"
          type="info"
          :closable="false"
          class="edit-alert"
        />
        <el-form-item label="模板编码">
          <el-input v-model="editForm.template_code" disabled />
        </el-form-item>
        <el-form-item label="模板名称" required>
          <el-input v-model="editForm.template_name" placeholder="请输入模板名称" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input
            v-model="editForm.description"
            type="textarea"
            :rows="4"
            placeholder="请输入模板描述"
          />
        </el-form-item>
        <el-form-item label="是否启用">
          <el-switch v-model="editForm.is_active" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSave" :loading="submitting">保存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Search, Refresh, List, ArrowUp, ArrowDown, View, Edit, CopyDocument } from '@element-plus/icons-vue'
import ReportsSearchCard from '../components/layout/ReportsSearchCard.vue'
import ReportsTableCard from '../components/layout/ReportsTableCard.vue'
import DialogHeader from '@/components/DialogHeader.vue'
import api from '@/utils/api'
import { createLogger } from '@/utils/logger'

const componentLogger = createLogger('ReportTemplatesPage')

const loading = ref(false)
const templates = ref([])
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)
const paginationVisible = ref(false)
const viewDialogVisible = ref(false)
const editDialogVisible = ref(false)
const currentTemplate = ref(null)
const detailLoading = ref(false)
const submitting = ref(false)

const searchForm = reactive({
  group: '',
  is_active: '',
  sortField: 'template_group',
  sortOrder: 'asc'
})

const editForm = reactive({
  id: null,
  template_code: '',
  template_name: '',
  description: '',
  is_active: true
})

const jsonExpanded = reactive({
  param: false,
  default: false
})

const fetchTemplates = async () => {
  try {
    loading.value = true
    const params = {
      page: currentPage.value,
      size: pageSize.value,
      sort_field: searchForm.sortField,
      sort_order: searchForm.sortOrder
    }

    if (searchForm.group) {
      params.group = searchForm.group
    }

    if (searchForm.is_active !== '') {
      params.is_active = searchForm.is_active
    }

    const response = await api.get('/reports/templates', { params })
    const data = response.data.data

    templates.value = data.rows || []
    total.value = data.total || templates.value.length

    componentLogger.info('模板列表加载成功', { count: templates.value.length })
  } catch (error) {
    componentLogger.error('获取模板列表失败', error)
    ElMessage.error('获取模板列表失败')
  } finally {
    loading.value = false
  }
}

const formatDateTime = (dateTimeStr) => {
  if (!dateTimeStr) return '-'

  if (/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/.test(dateTimeStr)) {
    return dateTimeStr
  }

  if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/.test(dateTimeStr) && !dateTimeStr.includes('Z') && !dateTimeStr.match(/[+-]\d{2}:\d{2}$/)) {
    const match = dateTimeStr.match(/^(\d{4}-\d{2}-\d{2})T(\d{2}:\d{2}:\d{2})/)
    if (match) {
      return `${match[1]} ${match[2]}`
    }
  }

  try {
    const date = new Date(dateTimeStr)
    if (isNaN(date.getTime())) {
      return dateTimeStr
    }

    const formatter = new Intl.DateTimeFormat('zh-CN', {
      timeZone: 'Asia/Shanghai',
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit',
      hour12: false
    })

    const parts = formatter.formatToParts(date)
    const year = parts.find(p => p.type === 'year').value
    const month = parts.find(p => p.type === 'month').value
    const day = parts.find(p => p.type === 'day').value
    const hour = parts.find(p => p.type === 'hour').value
    const minute = parts.find(p => p.type === 'minute').value
    const second = parts.find(p => p.type === 'second').value

    return `${year}-${month}-${day} ${hour}:${minute}:${second}`
  } catch (error) {
    return dateTimeStr
  }
}

const handleSearch = () => {
  currentPage.value = 1
  fetchTemplates()
}

const handleReset = () => {
  searchForm.group = ''
  searchForm.is_active = ''
  searchForm.sortField = 'template_group'
  searchForm.sortOrder = 'asc'
  currentPage.value = 1
  fetchTemplates()
}

const handleRefresh = () => {
  fetchTemplates()
  ElMessage.success('刷新成功')
}

const handleSortChange = ({ prop, order }) => {
  if (prop) {
    searchForm.sortField = prop
    searchForm.sortOrder = order === 'ascending' ? 'asc' : 'desc'
    fetchTemplates()
  }
}

const togglePagination = () => {
  paginationVisible.value = !paginationVisible.value
}

const formatJson = (json) => {
  if (!json) return '-'
  try {
    return JSON.stringify(json, null, 2)
  } catch (error) {
    return String(json)
  }
}

const getGroupType = (group) => {
  const map = {
    starrocks: 'primary',
    kafka: 'warning',
    flink: 'success',
    alerts: 'danger',
    mixed: 'info'
  }
  return map[group] || ''
}

const fetchTemplateDetail = async (id) => {
  const response = await api.get(`/reports/templates/id/${id}`)
  return response.data.data
}

const handleView = async (row) => {
  detailLoading.value = true
  try {
    currentTemplate.value = await fetchTemplateDetail(row.id)
    jsonExpanded.param = false
    jsonExpanded.default = false
    viewDialogVisible.value = true
    componentLogger.info('查看模板详情', { template_id: row.id })
  } catch (error) {
    componentLogger.error('获取模板详情失败', error)
    ElMessage.error('获取模板详情失败')
  } finally {
    detailLoading.value = false
  }
}

const handleEdit = async (row) => {
  detailLoading.value = true
  try {
    const data = await fetchTemplateDetail(row.id)
    Object.assign(editForm, {
      id: data.id,
      template_code: data.template_code,
      template_name: data.template_name,
      description: data.description || '',
      is_active: data.is_active === 1 || data.is_active === true
    })
    editDialogVisible.value = true
  } catch (error) {
    componentLogger.error('获取模板信息失败', error)
    ElMessage.error('获取模板信息失败')
  } finally {
    detailLoading.value = false
  }
}

const handleSave = async () => {
  if (!editForm.template_name || !editForm.template_name.trim()) {
    ElMessage.warning('请输入模板名称')
    return
  }

  submitting.value = true
  try {
    await api.put(`/reports/templates/id/${editForm.id}`, {
      template_name: editForm.template_name,
      description: editForm.description,
      is_active: editForm.is_active ? 1 : 0
    })
    ElMessage.success('更新成功')
    editDialogVisible.value = false
    fetchTemplates()
  } catch (error) {
    componentLogger.error('更新模板失败', error)
    ElMessage.error(error.response?.data?.message || '更新失败')
  } finally {
    submitting.value = false
  }
}

const handleToggleStatus = async (row, value) => {
  const previous = value === 1 ? 0 : 1
  try {
    await api.put(`/reports/templates/id/${row.id}`, {
      is_active: value === 1 ? 1 : 0
    })
    ElMessage.success('状态更新成功')
  } catch (error) {
    componentLogger.error('更新状态失败', error)
    ElMessage.error('更新状态失败')
    row.is_active = previous
  }
}

const handleCopyJson = async (json, label) => {
  const text = formatJson(json)
  try {
    await navigator.clipboard.writeText(text)
    ElMessage.success(`${label} JSON 已复制`)
  } catch (error) {
    componentLogger.error('复制 JSON 失败', error)
    ElMessage.error('复制失败，请手动复制')
  }
}

const toggleJsonSection = (section) => {
  jsonExpanded[section] = !jsonExpanded[section]
}

onMounted(() => {
  fetchTemplates()
})
</script>

<style scoped>
.report-templates-page {
  padding: 0;
}

.search-form-content {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 20px;
}

.search-form-fields {
  display: flex;
  gap: 20px;
  flex: 1;
}

.search-form-fields .el-form-item {
  margin-bottom: 0;
}

.search-form-actions {
  display: flex;
  gap: 10px;
  white-space: nowrap;
}

.table-info {
  display: flex;
  align-items: center;
}

.refresh-btn {
  background: linear-gradient(135deg, #67C23A 0%, #85CE61 100%);
  border: none;
  border-radius: 8px;
  color: #fff;
  box-shadow: 0 4px 12px rgba(103, 194, 58, 0.3);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  font-weight: 500;
}

.refresh-btn:hover {
  background: linear-gradient(135deg, #85CE61 0%, #67C23A 100%);
  box-shadow: 0 6px 20px rgba(103, 194, 58, 0.4);
  transform: translateY(-2px);
  color: #fff;
}

.pagination-control-wrapper {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 4px 8px;
  background: rgba(64, 158, 255, 0.08);
  border: 1px solid rgba(64, 158, 255, 0.2);
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  user-select: none;
  font-size: 12px;
  height: 24px;
}

.pagination-control-wrapper:hover {
  background: rgba(64, 158, 255, 0.12);
  border-color: rgba(64, 158, 255, 0.3);
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.15);
}

.page-count {
  font-size: 12px;
  font-weight: 500;
  color: #909399;
  line-height: 1;
}

.divider {
  width: 1px;
  height: 12px;
  background: rgba(64, 158, 255, 0.3);
  margin: 0 2px;
}

.pagination-info {
  font-size: 12px;
  font-weight: 500;
  color: #409eff;
  letter-spacing: 0.5px;
  min-width: 24px;
  text-align: center;
  line-height: 1;
}

.pagination-toggle-icon {
  font-size: 12px;
  color: #409eff;
  transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.pagination-section {
  padding: 16px;
  border-top: 1px solid #f0f0f0;
  background: #fafafa;
}

.pagination-section .el-pagination {
  display: flex;
  justify-content: center;
}

.pagination-slide-enter-active,
.pagination-slide-leave-active {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.pagination-slide-enter-from,
.pagination-slide-leave-to {
  opacity: 0;
  max-height: 0;
  overflow: hidden;
}

.pagination-slide-enter-to,
.pagination-slide-leave-from {
  opacity: 1;
  max-height: 200px;
}

.action-buttons {
  display: flex;
  gap: 8px;
  flex-wrap: nowrap;
  white-space: nowrap;
  justify-content: flex-start;
  align-items: center;
}

.action-buttons :deep(.el-button) {
  font-weight: 500;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.12);
  width: 32px;
  height: 32px;
  padding: 0;
  display: inline-flex;
  align-items: center;
  justify-content: center;
}

.action-buttons :deep(.el-button:hover) {
  transform: translateY(-2px) scale(1.05);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
}

.action-buttons :deep(.el-button:active) {
  transform: translateY(0) scale(0.98);
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.json-block {
  max-height: 260px;
  overflow: auto;
  background: #f5f5f5;
  padding: 10px;
  border-radius: 4px;
  font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, monospace;
  font-size: 13px;
}

.output-format-tag {
  margin-right: 6px;
  margin-bottom: 4px;
}

.edit-alert {
  margin-bottom: 20px;
}

.json-block-wrapper {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.json-block-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 13px;
  color: #909399;
}

.json-actions {
  display: flex;
  align-items: center;
  gap: 4px;
}

.json-action-divider {
  height: 20px;
  margin: 0 4px;
}

.json-toggle-icon {
  transition: transform 0.2s ease;
}

.json-toggle-icon.expanded {
  transform: rotate(180deg);
}

.json-collapsed-placeholder {
  padding: 12px;
  background: #f8f9fb;
  border: 1px dashed #dcdfe6;
  border-radius: 4px;
  color: #909399;
  font-size: 13px;
  text-align: center;
}

.json-collapse-enter-active,
.json-collapse-leave-active {
  transition: max-height 0.3s ease, opacity 0.3s ease;
}

.json-collapse-enter-from,
.json-collapse-leave-to {
  max-height: 0;
  opacity: 0;
}

.json-collapse-enter-to,
.json-collapse-leave-from {
  max-height: 400px;
  opacity: 1;
}

.description-text {
  white-space: pre-line;
  word-break: break-word;
}
</style>
